﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace _4_6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // 确保事件已经绑定（如果不是设计器自动生成的话）
            this.Load += Form1_Load;
            this.hScrollBar1.Scroll += hScrollBar1_Scroll;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitHScrollBar();
            InitPicture();
        }

        // 初始化滚动条
        private void InitHScrollBar()
        {
            hScrollBar1.SmallChange = 5;
            hScrollBar1.Minimum = 0;

            // WinForms 的 ScrollBar 真实最大值 = Maximum - LargeChange + 1
            // 这里设置成 119 是为了让最大值刚好是 100
            hScrollBar1.Maximum = 119; // Ensure maximum zoom of 100%
            hScrollBar1.LargeChange = 20;

            hScrollBar1.Dock = DockStyle.Bottom;
            hScrollBar1.Value = 100;   // 默认 100% 缩放
        }

        // 初始化图片
        private void InitPicture()
        {
            pictureBox1.Image = Image.FromFile("flower.jpg");
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;

            ZoomPic(hScrollBar1.Value);
        }

        // 缩放方法
        private void ZoomPic(int ratio)
        {
            float ratio_f = ratio / 100f;

            // 计算图片框大小（减去滚动条高度）
            int picWidth = (int)(this.ClientSize.Width * ratio_f);
            int picHeight = (int)((this.ClientSize.Height - hScrollBar1.Height) * ratio_f);

            pictureBox1.Size = new Size(picWidth, picHeight);

            // 居中显示
            pictureBox1.Left = (this.ClientSize.Width - picWidth) / 2;
            pictureBox1.Top = (this.ClientSize.Height - hScrollBar1.Height - picHeight) / 2;

            this.Text = $"Image browser {ratio}%";
        }

        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            ZoomPic(hScrollBar1.Value);
        }
    }
}